Laravel 提供了完善的資料庫操作工具,讓後端 API 開發中常見的 CRUD 操作(建立、讀取、更新、刪除)變得簡單、結構化。
為了讓開發環境與部署環境有一致的資料表結構,我們使用 Migration 來管理資料庫 schema。
php artisan make:migration create_demo_table
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDemoTable extends Migration
{
public function up()
{
Schema::create('demo', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps(); // 建立 created_at 和 updated_at 欄位
});
}
public function down()
{
Schema::dropIfExists('demo');
}
}
php artisan migrate
php artisan migrate:rollback
Seeder 可用來填入開發或測試用的初始資料,例如系統預設的帳號、範例資料等。
php artisan make:seeder DemoSeeder
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class DemoSeeder extends Seeder
{
public function run(): void
{
DB::table('demo')->insert([
'name' => 'demo',
]);
}
}
php artisan db:seed --class=DemoSeeder
php artisan db:seed
Laravel 測試預設使用 SQLite
在 phpunit.xml 中 Laravel 通常會使用 SQLite 的 in-memory 模式作為測試資料庫:
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
這樣每次測試都能從乾淨資料庫開始。
use Illuminate\Foundation\Testing\RefreshDatabase;
class ExampleTest extends TestCase
{
use RefreshDatabase;
public function test_example()
{
// 會自動跑 migrate 並清空資料
}
}
這個 trait 會在測試前自動執行 migrate,並在每個測試後清空資料庫。
配合測試或 seeding,你可以用 Factory 建立大量假資料。
php artisan make:factory DemoFactory --model=Demo
use App\Models\Demo;
Demo::factory()->create([
'name' => 'example',
]);
Demo::factory()->count(10)->create(); // 建立 10 筆資料
以上就是在專案中常用的資料庫操作,非常方便!